package com.itheima.pinda.authority.controller.auth;

import com.itheima.pinda.auth.utils.Token;
import com.itheima.pinda.authority.biz.service.auth.impl.AuthManager;
import com.itheima.pinda.authority.dto.auth.LoginDTO;
import com.itheima.pinda.authority.dto.auth.LoginParamDTO;
import com.itheima.pinda.base.BaseController;
import com.itheima.pinda.authority.biz.service.auth.ValidateCodeService;
import com.itheima.pinda.base.R;
import com.itheima.pinda.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 登录（认证）控制器
 * @Author: ysf
 * @CreateTime: 2024-11-13  11:09
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("anno")
@Api(value = "LoginController", tags = "登录")
@RequiredArgsConstructor
public class LoginController extends BaseController {

    final ValidateCodeService validateCodeService;

    final AuthManager authManager;//认证管理器对象

    @SysLog(value = "生成验证码")
    @ApiOperation(value = "验证码",notes = "验证码")
    @GetMapping(value = "captcha",produces = "image/png") //produces指定接口返回的数据类型
    public void captcha(@RequestParam("key") String key, HttpServletResponse response) throws IOException {
        this.validateCodeService.create(key,response);
    }

    @SysLog("用户登录")
    @ApiOperation(value = "用户登录",notes = "用户登录")
    @PostMapping("login")
    public R<LoginDTO> login(@Validated @RequestBody LoginParamDTO loginParamDTO){

        log.info("用户账号：{}",loginParamDTO.getAccount());

        if(this.validateCodeService.check(loginParamDTO.getKey(),loginParamDTO.getCode())){
            return this.authManager.login(loginParamDTO.getAccount(),loginParamDTO.getPassword());
        }

        return this.success(null);
    }

}
